package com.example.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.springboot.entity.Device;
import com.example.springboot.mapper.DeviceMapper;
import com.example.springboot.mapper.SupplierMapper;
import com.example.springboot.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/devices")
public class DeviceController {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private DeviceService deviceService;

    //用get请求查询数据库信息
    @GetMapping
    public List<Device> findAll(){
        return deviceMapper.findAll();//查询所有数据
    }

    //用post请求对数据库数据进行增加和修改
    @PostMapping
    public Integer save(@RequestBody Device device){
        return deviceService.save(device);//往数据库插入或更新数据
    }

    //用post请求修改数据库status
    @PostMapping("/status")
    public int updateStatus(@RequestBody String deviceNumber){
        return deviceMapper.updateStatus(deviceNumber);//往数据库插入或更新数据
    }

    //用post请求修改数据库status和situation
    @PostMapping("/outstore")
    public int updateOutstore(@RequestBody Map<String,Object> map){
        String deviceNumber = map.get("deviceNumber").toString();
        String status = map.get("status").toString();
        String situation = map.get("situation").toString();
        return deviceMapper.updateOutstore(deviceNumber,status,situation);//往数据库插入或更新数据
    }

    //删除
    @DeleteMapping("/{id}")
    public Integer delete(@PathVariable Integer id){
        return deviceMapper.deleteById(id);
    }

    //批量删除
    @PostMapping("/del/batch")
    public Integer deleteBatch(@RequestBody List<Integer> ids){
        Integer num = 0;
        for(int i=0; i<ids.size();i++){
            Integer id = ids.get(i);
            num = deviceMapper.deleteById(id);
        }
        return num;
    }

    //多条件分页查询
    //接口路径：/devices/page?pageNum=1&pageSize=10
    //@RequestParam接收 ?pageNum=1&pageSize=10
    //分页查询的sql语句为 select * from sys_device limit 0,5;  --第一页显示5条
    //                 select * from sys_device limit 5,5;  --第二页显示5条
    // limit第一个参数 = (pageNum - 1) * pageSize，第二个参数=pageSize
    @GetMapping("/page")
    public Map<String,Object> findPage(@RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize,
                                       @RequestParam String deviceNumber){
        pageNum = (pageNum - 1) * pageSize;
        Integer total = deviceMapper.selectTotal(deviceNumber);
        List<Device> data = deviceMapper.selectPage(pageNum,pageSize,deviceNumber);
        for(Device device : data){
            device.setSupplierNumber(supplierMapper.findById(device.getSupplierId()));
        }
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    //按照使用状态分页查询
    @GetMapping("/page/status")
    public Map<String,Object> findStatus(@RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize,
                                       @RequestParam String status){
        pageNum = (pageNum - 1) * pageSize;
        Integer total = deviceMapper.selectTotalStatus(status);
        List<Device> data = deviceMapper.selectStatus(pageNum,pageSize,status);
        for(Device device : data){
            device.setSupplierNumber(supplierMapper.findById(device.getSupplierId()));
        }
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     *导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库中查询出所有数据
        List<Device> list = deviceMapper.findAll();
        //通过工具类创建writer 写出磁盘路径
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id","ID");
        writer.addHeaderAlias("deviceName","设备名称");
        writer.addHeaderAlias("deviceNumber","设备编号");
        writer.addHeaderAlias("deviceSize","型号");
        writer.addHeaderAlias("deviceType","设备类型");
        writer.addHeaderAlias("status","使用状态");
        writer.addHeaderAlias("brand","品牌");
        writer.addHeaderAlias("utility","用途");
        writer.addHeaderAlias("situation","存放地点");
        writer.addHeaderAlias("supplierId","供应商id");
        writer.addHeaderAlias("buyerName","采购人姓名");
        writer.addHeaderAlias("buyDate","采购日期");
        writer.addHeaderAlias("durability","使用年限");
        writer.addHeaderAlias("price","单价");
        writer.addHeaderAlias("createTime","创建时间");

        //一次性写出list中的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);
        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("设备信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    /**
     * excel导入接口
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Integer imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
//        reader.addHeaderAlias("ID","id");
        reader.addHeaderAlias("设备名称","deviceName");
        reader.addHeaderAlias("设备编号","deviceNumber");
        reader.addHeaderAlias("型号","deviceSize");
        reader.addHeaderAlias("设备类型","deviceType");
        reader.addHeaderAlias("使用状态","status");
        reader.addHeaderAlias("品牌","brand");
        reader.addHeaderAlias("用途","utility");
        reader.addHeaderAlias("存放地点","situation");
        reader.addHeaderAlias("供应商id","supplierId");
        reader.addHeaderAlias("采购人姓名","buyerName");
        reader.addHeaderAlias("采购日期","buyDate");
        reader.addHeaderAlias("使用年限","durability");
        reader.addHeaderAlias("单价","price");

        List<Device> list = reader.readAll(Device.class);
        System.out.println(list);

        return deviceService.saveBatch(list);
    }
}
